# centos系统检查
# 作者: 丁文
# 时间: 2025-04-09 22:00:05
#!/usr/bin/env bash

##############################################################################
# Console color
C_RESET="$(tput sgr0)"
C_BLACK="\033[1;30m"
C_RED="\033[1;31m"
C_GREEN="\033[1;32m"
C_YELLOW="\033[1;33m"
C_BLUE="\033[1;34m"
C_PURPLE="\033[1;35m"
C_CYAN="\033[1;36m"
C_WHITE="\033[1;37m"
##############################################################################

printf "${C_PURPLE}"
cat << EOF
###################################################################################
# System Information Check Script
###################################################################################
EOF
printf "${C_RESET}"

[[ $(id -u) -gt 0 ]] && echo "Please run this script as root!" && exit 1
sysversion=$(rpm -q centos-release | cut -d- -f3)
double_line="==============================================================="
line="----------------------------------------------"

# Print header info
printHeadInfo() {
  cat << EOF
+---------------------------------------------------------------------------------+
|                           Welcome to the 【System Information Check Script】     |
+---------------------------------------------------------------------------------+
EOF
}

# Print footer info
printFootInfo() {
  cat << EOF
+---------------------------------------------------------------------------------+
|                            Script execution finished, thank you for using!      |
+---------------------------------------------------------------------------------+
EOF
}

options=( "Get System Information" "Get Service Information" "Get CPU Information" "Get System Network Information" "Get System Memory Information" "Get System Disk Information" "Get CPU/Memory Top10" "Get System User Information" "Output All Information" "Exit" )
printMenu() {
  printf "${C_BLUE}"
  printf "Main Menu:\n"
  for i in "${!options[@]}"; do
    index=`expr ${i} + 1`
    val=`expr ${index} % 2`
    printf "\t(%02d) %-30s" "${index}" "${options[$i]}"
    if [[ ${val} -eq 0 ]]; then
      printf "\n"
    fi
  done
  printf "${C_BLUE}Please enter the command to execute:\n"
  printf "${C_RESET}"
}

# Get system information
get_systatus_info() {
  sys_os=$(uname -o)
  sys_release=$(cat /etc/redhat-release)
  sys_kernel=$(uname -r)
  sys_hostname=$(hostname)
  sys_selinux=$(getenforce)
  sys_lang=$(echo $LANG)
  sys_lastreboot=$(who -b | awk '{print $3,$4}')
  sys_runtime=$(uptime | awk '{print  $3,$4}' | cut -d, -f1)
  sys_time=$(date)
  sys_load=$(uptime | cut -d: -f5)

  cat << EOF
【System Information】
System: ${sys_os}
Release Version:   ${sys_release}
Kernel Version:   ${sys_kernel}
Hostname:    ${sys_hostname}
SELinux Status:  ${sys_selinux}
System Language:   ${sys_lang}
Current System Time: ${sys_time}
Last Reboot Time:   ${sys_lastreboot}
System Uptime: ${sys_runtime}
System Load:   ${sys_load}
EOF
}

# Get CPU information
get_cpu_info() {
  Physical_CPUs=$(grep "physical id" /proc/cpuinfo | sort | uniq | wc -l)
  Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
  CPU_Kernels=$(grep "cores" /proc/cpuinfo | uniq | awk -F ': ' '{print $2}')
  CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
  CPU_Arch=$(uname -m)
  cat << EOF
【CPU Information】
Physical CPUs: $Physical_CPUs
Logical CPUs: $Virt_CPUs
Cores per CPU: $CPU_Kernels
CPU Model: $CPU_Type
CPU Architecture: $CPU_Arch
EOF
}

# Get service information
get_service_info() {
  port_listen=$(ss -lntup)
  kernel_config=$(sysctl -p 2> /dev/null)
  if [[ ${sysversion} -gt 6 ]]; then
    service_config=$(systemctl list-unit-files --type=service --state=enabled | grep "enabled")
    run_service=$(systemctl list-units --type=service --state=running | grep ".service")
  else
    service_config=$(/sbin/chkconfig | grep -E ":on|:启用" | column -t)
    run_service=$(/sbin/service --status-all | grep -E "running")
  fi
  cat << EOF
【Service Information】
${service_config}
  ${line}
Running Services:
${run_service}
  ${line}
Listening Ports:
${port_listen}
  ${line}
Kernel Configuration:
${kernel_config}
EOF
}

# Get system memory information
get_mem_info() {
  check_mem=$(free -m)
  MemTotal=$(grep MemTotal /proc/meminfo | awk '{print $2}') #KB
  MemFree=$(grep MemFree /proc/meminfo | awk '{print $2}') #KB
  let MemUsed=MemTotal-MemFree
  MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")
  report_MemTotal="$((MemTotal/1024))"  # Convert to MB
  report_MemFree="$((MemFree/1024))"  # Convert to MB
  report_MemUsedPercent=$(free | sed -n '2p' | gawk 'x = int(( $3 / $2 ) * 100) {print x}' | sed 's/$/%/')

  cat << EOF
【Memory Information】
Total Memory (MB): ${report_MemTotal}
Free Memory (MB): ${report_MemFree}
Memory Usage Percentage: ${report_MemUsedPercent}
EOF
}

# Get system network information
get_net_info() {
  pri_ipadd=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}')
  pub_ipadd=$(curl ifconfig.me -s)
  gateway=$(ip route | grep default | awk '{print $3}')
  mac_info=$(ip link | egrep -v "lo" | grep link | awk '{print $2}')
  dns_config=$(egrep -v "^$|^#" /etc/resolv.conf)
  route_info=$(ip route)

  cat << EOF
【Network Information】
Public IP Address: ${pub_ipadd}
Private IP Address: ${pri_ipadd}
Gateway Address: ${gateway}
MAC Address: ${mac_info}
Routing Information:
${route_info}
DNS Information:
${dns_config}
EOF
}

# Get system disk information
get_disk_info() {
  disk_info=$(fdisk -l | grep "Disk /dev" | cut -d, -f1)
  disk_use=$(df -hTP | awk '$2!="tmpfs"{print}')
  disk_percent=$(free | sed -n '2p' | gawk 'x = int(( $3 / $2 ) * 100) {print x}' | sed 's/$/%/')
  disk_inode=$(df -hiP | awk '$1!="tmpfs"{print}')

  cat << EOF
【Disk Information】
${disk_info}
Disk Usage: ${disk_use}
Disk Usage Percentage: ${disk_percent}
Inode Information: ${disk_inode}
EOF
}

# Get system user information
get_sys_user() {
  login_user=$(awk -F: '{if ($NF=="/bin/bash") print $0}' /etc/passwd)
  ssh_config=$(egrep -v "^#|^$" /etc/ssh/sshd_config)
  sudo_config=$(egrep -v "^#|^$" /etc/sudoers | grep -v "^Defaults")
  host_config=$(egrep -v "^#|^$" /etc/hosts)
  crond_config=$(for cronuser in /var/spool/cron/*; do
    ls ${cronuser} 2> /dev/null | cut -d/ -f5; egrep -v "^$|^#" ${cronuser} 2> /dev/null;
    echo "";
  done)
  cat << EOF
【User Information】
System Login Users:
${login_user}
  ${line}
SSH Configuration:
${ssh_config}
  ${line}
Sudo Configured Users:
${sudo_config}
  ${line}
Cron Task Configurations:
${crond_config}
  ${line}
Hosts File Information:
${host_config}
EOF
}

# Get CPU/Memory Top10 usage
get_process_top_info() {

  top_title=$(top -b n1 | head -7 | tail -1)
  cpu_top10=$(top -b n1 | head -17 | tail -11)
  mem_top10=$(top -b n1 | head -17 | tail -10 | sort -k10 -r)

  cat << EOF
【TOP10】
CPU Usage Top10:
${cpu_top10}
Memory Usage Top10:
${top_title}
  ${mem_top10}
EOF
}

show_dead_process() {
  printf "Zombie Processes:\n"
  ps -al | gawk '{print $2,$4}' | grep Z
}

get_all_info() {
  get_systatus_info
  echo ${double_line}
  get_service_info
  echo ${double_line}
  get_cpu_info
  echo ${double_line}
  get_net_info
  echo ${double_line}
  get_mem_info
  echo ${double_line}
  get_disk_info
  echo ${double_line}
  get_process_top_info
  echo ${double_line}
  get_sys_user
}

main() {
  while [[ 1 ]]
  do
    printMenu
    read option
    local index=$[ ${option} - 1 ]
    case ${options[${index}]} in
      "Get System Information")
        get_systatus_info ;;
      "Get Service Information")
        get_service_info ;;
      "Get CPU Information")
        get_cpu_info ;;
      "Get System Network Information")
        get_net_info ;;
      "Get System Memory Information")
        get_mem_info ;;
      "Get System Disk Information")
        get_disk_info ;;
      "Get CPU/Memory Top10")
        get_process_top_info ;;
      "Get System User Information")
        get_sys_user ;;
      "Output All Information")
        get_all_info > sys.log
        printf "${C_GREEN}Information has been output to sys.log.${C_RESET}\n\n"
      ;;
      "Exit")
        exit ;;
      *)
        clear
        echo "Sorry, this option is not supported." ;;
    esac
  done
}

######################################## MAIN ########################################
printHeadInfo
main
printFootInfo
printf "${C_RESET}"

